package edu.cicese.alz.swing.tables;

import edu.cicese.alz.FrameSubjects;
import edu.cicese.alz.swing.SwingUtil;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.Component;
import java.util.Map;
import java.util.TreeSet;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 29/05/12
 * Time: 01:02 PM
 */
public class SubjectsTable extends JTable {

	private Map<Integer, int[]> idxChanges;
	private TreeSet<Integer> idxNewSubjects;

	public SubjectsTable(Map<Integer, int[]> idxChanges, TreeSet<Integer> idxNewSubjects) {
		super();
		this.idxChanges = idxChanges;
		this.idxNewSubjects = idxNewSubjects;
	}

	@Override
	public boolean isCellEditable(int row, int col) {
		return col != 0;
	}

	@Override
	public TableCellRenderer getCellRenderer(int row, int col) {
		TableCellRenderer renderer = super.getCellRenderer(row, col);
		if (col != 5) {
			if (col != 1) {
				((JLabel) renderer).setHorizontalAlignment(SwingConstants.CENTER);
			} else {
				((JLabel) renderer).setHorizontalAlignment(SwingConstants.LEFT);
			}
		}
		return renderer;
	}

	@Override
	public Component prepareEditor(TableCellEditor editor, int row, int column) {
		Component c = super.prepareEditor(editor, row, column);

		setFont(c, row, column);
		
		return c;
	}

	@Override
	public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
		Component c = super.prepareRenderer(renderer, row, column);

		setFont(c, row, column);

		return c;
	}

	private void setFont(Component c, int row, int column) {
		c.setFont(SwingUtil.fontNormal);

		if (!isRowSelected(row)) {
			c.setBackground(getBackground());

			if (deletingRow(row)) {
				c.setBackground(SwingUtil.colorDelete);
			}
			else if (insertingRow(row)) {
				c.setBackground(SwingUtil.colorInsert);
			}
			else if (updatingRow(row)) {
				c.setFont(SwingUtil.fontUpdate);
			}
		}

		if (column == 0) {
			c.setFont(SwingUtil.fontUserID);
		}
	}

	private boolean deletingRow(int row) {
		return (idxChanges.containsKey(row) && idxChanges.get(row)[0] == FrameSubjects.DELETE);
	}

	private boolean insertingRow(int row) {
		return idxNewSubjects.contains(row);
	}

	private boolean updatingRow(int row) {
		return (idxChanges.containsKey(row) && idxChanges.get(row)[0] == FrameSubjects.UPDATE);
	}
}
